package cn.labbook.bluetooth.exception;

import cn.labbook.bluetooth.constant.ResultConstant;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.TypeMismatchDataAccessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  spring异常 处理器
 * </p>
 *
 * @author Administrator
 * @since 2018-10-30
 */
@ControllerAdvice
@Log4j2
public class SysExceptionHandlerAdvice {
    @ExceptionHandler({HttpMessageNotReadableException.class, TypeMismatchException.class})
    public String handle400Exception(Exception ex,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws IOException {
        Integer respCode = 400;
        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(requestType)) {
            errorJsonResult(respCode, request, response);
        } else {
            return "error";
        }
        return null;
    }

    @ExceptionHandler(TypeMismatchDataAccessException.class)
    public String handle500Exception(TypeMismatchDataAccessException ex,
                                     HttpSession session, HttpServletRequest request,
                                     HttpServletResponse response) throws IOException {
        Integer respCode = 500;
        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(requestType)) {
            errorJsonResult(respCode, request, response);
        } else {
            return "error";
        }
        return null;
    }

    private void errorJsonResult(Integer respCode,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {
        Map<String, Object> result = new HashMap<>();
        result.put("code", ResultConstant.FAIL_CODE);
        String msg;
        if (400 == respCode) {
            msg = "请求参数不合法";
        } else if (500 == respCode) {
            msg = "服务器异常";
        } else {
            msg = "未知错误";
        }
        result.put("msg", msg);
        String requestURI = request.getRequestURI();
        log.error("{} error ==>>[{}] {}", respCode, requestURI, msg);
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
}
